package com.demo.download.config;

import lombok.Builder;
import lombok.Data;
import org.springframework.http.client.SimpleClientHttpRequestFactory;
import org.springframework.web.client.RestTemplate;

import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.security.SecureRandom;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;

@Builder
@Data
public class RestTemplateBuilder {

    private int connectionTimeout = 50000;

    private int readTime = 50000;

    private boolean enableSslCheck = false;

    public RestTemplateBuilder() {
    }

    public RestTemplate build(){

        final RestTemplate template = new RestTemplate();
        SimpleClientHttpRequestFactory factory;
        if(!this.enableSslCheck){
            factory = getUnsafeClientHttpRequestFactory();
        } else {
            factory = new SimpleClientHttpRequestFactory();
        }
        factory.setConnectTimeout(connectionTimeout);
        factory.setReadTimeout(readTime);

        template.setRequestFactory(factory);
        return template;
    }


    private SimpleClientHttpRequestFactory getUnsafeClientHttpRequestFactory(){
        TrustManager[] byPassTrustManager = new TrustManager[]{
                new X509TrustManager() {
                    @Override
                    public void checkClientTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException {

                    }

                    @Override
                    public void checkServerTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException {

                    }

                    @Override
                    public X509Certificate[] getAcceptedIssuers() {
                        return new X509Certificate[0];
                    }
                }
        };
        final SSLContext sslContext;
        try{
            sslContext = SSLContext.getInstance("TLS");
            sslContext.init(null,byPassTrustManager,new SecureRandom());
            sslContext.getSocketFactory();
        }catch (Exception e){
            throw new RuntimeException(e);
        }
        return new SimpleClientHttpRequestFactory(){
            @Override
            protected void prepareConnection(HttpURLConnection connection, String httpMethod) throws IOException {
                super.prepareConnection(connection, httpMethod);
                if(connection instanceof HttpsURLConnection){
                    ((HttpsURLConnection) connection).setSSLSocketFactory(sslContext.getSocketFactory());
                }
            }
        };
    }

}
